#include "stdafx.h"
#include "ZMTriangelGroup.h"


ZMTriangelGroup::ZMTriangelGroup(const ZMVector<ZMPoint3D>& vPnt, const ZMVector<int>& vInx)
{
	InsertData(vPnt, vInx);
}


ZMTriangelGroup::~ZMTriangelGroup()
{
}

void ZMTriangelGroup::WriteData(CFileSaveData& fp)
{
	CStreamSaveData fsp;
	WriteData(fsp);
	fp << fsp.GetData();
}

void ZMTriangelGroup::WriteData(CStreamSaveData& fp)
{
	{
		ZMVector<ZMPoint3D>&vPnt = this->m_vPnt;
		ZMPoint3D pnt[3];
		ZMVector<int>& vInx = this->m_vInx;
		for (int i = 0; i < vInx.size() / 3; ++i)
		{
			pnt[0] = vPnt[vInx[3 * i]];
			pnt[1] = vPnt[vInx[3 * i + 1]];
			pnt[2] = vPnt[vInx[3 * i + 2]];

			fp << "3dpoly ";
			fp << pnt[0].x() << ",";		fp << pnt[0].y() << ",";		fp << pnt[0].z() << "\r\n";
			fp << pnt[1].x() << ",";		fp << pnt[1].y() << ",";		fp << pnt[1].z() << "\r\n";
			fp << pnt[2].x() << ",";		fp << pnt[2].y() << ",";		fp << pnt[2].z() << "\r\n";
			fp << pnt[0].x() << ",";		fp << pnt[0].y() << ",";		fp << pnt[0].z() << "\r\n";
			fp << "\r\n";
		}
	}
}

bool ZMTriangelGroup::GetHeight(const ZMReal& x, const ZMReal& y, ZMReal& z) const
{
	ZMReal dTol = 0.02;
	bool ret = false;
	CGALPoint pnt(x, y, 0);
	for (int i = 0; i < m_vInx.size(); i+=3)
	{
		ZMTriangle tri2(m_vPnt[m_vInx[i]].ToCGALPnt(ZMPoint3D::TYPE_2D), m_vPnt[m_vInx[i + 1]].ToCGALPnt(ZMPoint3D::TYPE_2D), m_vPnt[m_vInx[i + 2]].ToCGALPnt(ZMPoint3D::TYPE_2D));
		ZMReal dis = CGAL::squared_distance(tri2, pnt);
		if (dis < dTol * dTol)
		{
			ret = true;
			ZMTriangle tri(m_vPnt[m_vInx[i]].ToCGALPnt(), m_vPnt[m_vInx[i + 1]].ToCGALPnt(), m_vPnt[m_vInx[i + 2]].ToCGALPnt());
			GetHeight(tri, x, y, z);
			break;
		}
	}
	return ret;
}

int ZMTriangelGroup::GetHeight(const ZMTriangle&tri, const ZMReal& x, const ZMReal& y, ZMReal& z) const
{
	CGALPoint p[3];
	for (int i = 0; i < 3; ++i)
	{
		p[i] = tri[i];
	}
	ZMReal w[3];
	ZMReal wTemp = ((p[0].y() - p[2].y())*(p[1].x() - p[2].x()) + (p[1].y() - p[2].y())*(p[2].x() - p[0].x()));
	w[0] = ((y - p[2].y())*(p[1].x() - p[2].x()) + (p[1].y() - p[2].y())*(p[2].x() - x));
	w[0] /= wTemp;

	w[1] = ((y - p[0].y())*(p[2].x() - p[0].x()) + (p[2].y() - p[0].y())*(p[0].x() - x));
	w[1] /= wTemp;

	w[2] = ((y - p[1].y())*(p[0].x() - p[1].x()) + (p[0].y() - p[1].y())*(p[1].x() - x));
	w[2] /= wTemp;

	z = w[0] * p[0].z() + w[1] * p[1].z() + w[2] * p[2].z();
	return 0;
}
